<template>
	<view :data-theme='theme()' :class="theme() || ''">
		<view class="top-tabbar" style="gap:20rpx;overflow-y: hidden;">
			<view :class="state_active == 'all' ? 'tab-item active' : 'tab-item'" @click="stateFunc('all')">全部订单</view>
			<view :class="state_active == 'payment' ? 'tab-item active' : 'tab-item'" @click="stateFunc('payment')">待付款
			</view>
			<view :class="state_active == 'notConfirm' ? 'tab-item active' : 'tab-item'"
				@click="stateFunc('notConfirm')">待确认</view>
			<!-- <view :class="state_active == 'notFinalPayment' ? 'tab-item active' : 'tab-item'"
				@click="stateFunc('notFinalPayment')">待付尾款</view> -->
			<view :class="state_active == 'delivery' ? 'tab-item active' : 'tab-item'" @click="stateFunc('delivery')">
				待发货</view>
			<view :class="state_active == 'notPickup' ? 'tab-item active' : 'tab-item'" @click="stateFunc('notPickup')">
				待自提</view>

			<!-- <view :class="state_active == 'received' ? 'tab-item active' : 'tab-item'" @click="stateFunc('received')">
				待收货</view> -->
			<view :class="state_active == 'notComment' ? 'tab-item active' : 'tab-item'"
				@click="stateFunc('notComment')">待评价</view>
			<view :class="state_active == 'commented' ? 'tab-item active' : 'tab-item'" @click="stateFunc('commented')">
				已评价</view>
			<view :class="state_active == 'refund' ? 'tab-item active' : 'tab-item'" @click="stateFunc('refund')">退款
			</view>
		</view>
		<!--列表-->
		<scroll-view scroll-y="true" class="scroll-Y" :style="'height:' + scrollviewHigh + 'px;'" lower-threshold="50"
			@scrolltolower="scrolltolowerFunc">
			<view :class="topRefresh ? 'top-refresh open' : 'top-refresh'">
				<view class="circle" v-for="(circle, n) in 3" :key="n"></view>
			</view>
			<view class="order-list">
				<view class="item" v-for="(item, index) in listData" :key="index">
					<view class="order-head d-b-c">
						<view>
							<text class="state-text">{{ item.orderSourceText }}</text>
							<text class="shop-name flex-1 fb">订单号：{{ item.orderNo }}</text>
							<button size="mini" style="vertical-align: middle;margin-left: 10rpx;" @click="copy(item.orderNo)">复制</button>
						</view>
						<view class="state">
							<text :style="{color:item.groupStatus == 20?'#19ad57':'#f6220c'}"
								v-if="item.orderType == 2 || item.orderType == 7 || item.orderType == 8">{{ item.groupStatusText }}</text>
						</view>
					</view>
					<!--多个商品显示-->
					<view class="product-list pr" v-if="item.product.length > 1" @click="gotoOrder(item.orderId)">
						<scroll-view scroll-x="true">
							<view class="list d-s-c pr100">
								<view class="cover mr10" v-for="(img, num) in item.product" :key="num">
									<image :src="img.productImage" mode="aspectFit"></image>
								</view>
							</view>
						</scroll-view>
						<view class="total-count">
							<view class="left-shadow">
								<!-- {{item.payEndTime}} -->
							</view>
							<view class="price f22 theme-price">
								¥
								<text
									class="f40 theme-price">{{ token && UserState == '20'?item.orderPrice:'**' }}</text>
							</view>
							<view class="count">共{{ item.totalNum }}件</view>
						</view>
					</view>
					<!--一个商品显示-->
					<view class="one-product d-s-c" v-else @click="gotoOrder(item.orderId)">
						<view class="cover" v-for="(img, num) in item.product" :key="num">
							<image :src="img.productImage" mode="aspectFit"></image>
						</view>
						<view class="pro-info flex-1">{{ item.product[0]&&item.product[0].productName }}</view>

						<view class="total-count">
							<view class="left-shadow">
								<!-- {{item.payEndTime}} -->
							</view>
							<view class="price theme-price f22">
								¥
								<!-- <text class="f40 theme-price"
									v-if="item.orderType == 4">{{ (item.payPrice*1 + item.advance.payPrice*1).toFixed(2) }}</text> -->
								<text
									class="f40 theme-price">{{ token && UserState == '20'?item.orderPrice:"**" }}</text>
							</view>
							<view class="count">共{{ item.totalNum }}件</view>
						</view>
					</view>
					<view class="order-bts presale" v-if="item.orderType==1">
						<view class="d-b-c line-h-50 f24 gray9" v-if="item.advance">
							<view>定金</view>
							<view>
								<text>{{item.advance.payStatus == 20?'已支付':'待支付'}}</text>￥{{item.advance.payPrice}}
							</view>
						</view>
						<view class="d-b-c line-h-50  f24 gray9" v-if="item.advance">
							<view>尾款</view>
							<view>
								<text>{{item.advance.payStatus == 20&&item.payStatus == 20?'已支付':'待支付'}}</text>￥{{item.payPrice}}
							</view>
						</view>
						<!-- 待付款 -->
						<template v-if="item.status==10 && item.advance">
							<view class="d-e-c  line-h-50  f24 gray9"
								v-if="item.advance&&item.advance.payStatus==20 && item.payStatus != 20">
								<view v-if="nowOverTime(item.advance && item.advance.endTime)">
									尾款支付截止时间:<text class="redF11">{{item.payEndTime}}</text>
								</view>
								<view v-else-if="!nowOverTime(item.advance && item.advance.endTime)">
									尾款支付时间:<text class="redF11">{{item.advance.endTime}}</text>
								</view>
							</view>
						</template>
						<view class="d-e-c  line-h-50  f24 gray9"
							v-if="item.advance && (item.advance.payStatus == 10&&item.advance.status==10 && item.status!=20)">
							<view
								v-if="!nowOverTime(item.advance && item.advance.payEndTime)&&!nowOverTime(item.advance && item.advance.endTime)">
								定金支付截止时间: <text
									class="redF11">{{countDown(item.advance && item.advance.payEndTime)}}</text>
							</view>
						</view>
						<!-- 付尾款 -->
						<template v-if="item.status == 30">
							<view class="d-e-c" v-if="false">
								<!-- 订单付款 -->
								<template v-if="state_active == 'notFinalPayment'">
									<template>
										<view class="d-e-c mt10">
											<button class="pay-btn theme-btn"
												@click="gotoPage(`/orderpages/order/cashier?orderId=${item.orderId}&orderType=60`)">支付尾款</button>
										</view>
									</template>
								</template>
								<!-- 
									定金拿里面的advance.payStatus 状态 10 未支付 20 已支付
									尾款拿外面的payStatus 状态 10 未支付 20 已支付
									@ApiModelProperty("预售订单定金支付结束时间")
									private Date payEndTime;
									@ApiModelProperty("预售结束时间")
									private Date endTime;
									@ApiModelProperty("订单状态10=>进行中，20=>已经取消，30=>已完成")
									private Integer orderStatus;
									status 字段
									CANCEL("已取消",0),
									UNPAID("待付款", 10),
									NOTCONFIRM("待确认", 20),
									NOTFINALPAYMENT("待付尾款", 30),
									NOTPICKUP("待自提", 40),
									NOTDELIVERY("待发货",50),
									NOTRECEIVE("待收货",60),
									REFUNDED("已退款",70),
									COMPLETE("已完成",80),
									
									REFUNDING("退款中",90),
								 -->
								<view class="d-e-c mt10"
									v-if="item.advance && (item.advance.payStatus == 20 && item.advance.status==10 && item.advance.moneyReturn==1 && item.payStatus != 20)">
									<button class="pay-btn theme-borderbtn"
										@click="cancelAdvance(item.advance.orderAdvanceId)">取消定金</button>
								</view>
								<template v-if="item.status ==10&&item.payStatus == 20">
									<template v-if="item.deliveryStatus == 10">
										<button @click="cancelOrder(item.orderId)" class="theme-borderbtn">申请取消</button>
									</template>
								</template>
								<!-- 预售未支付取消订单 -->
								<template v-if="item.orderType == 4 && item.advance">
									<template v-if="item.status == 10 && item.advance.payStatus == 10">
										<!-- <button @click="cancelOrder(item.orderId)" class="theme-borderbtn">申请取消</button> -->
										<button @click="cancelAdvance(item.advance.orderAdvanceId)"
											class="theme-borderbtn">申请取消</button>
									</template>
								</template>
								<!-- <view class="d-e-c mt10"
									v-if="item.advance && (item.advance.payStatus == 10 && !nowOverTime(item.advance.payEndTime) && item.status == 30)">
									<button class="pay-btn theme-btn"
										@click="gotoPage('/orderpages/order/cashier?orderType=40&orderId=' + item.advance.orderId)">支付定金
									</button>
								</view> -->
								<!-- <view class="d-e-c mt10" v-if="item.deliveryStatus == 20 && item.receiptStatus == 10">
									<button v-if="item.payType ==20 && item.paySource =='wx'" @click="wxOrder(item)"
										class="pay-btn theme-btn">确认收货</button>
									<button v-else @click="orderReceipt(item)" class="pay-btn theme-btn">确认收货</button>
								</view> -->
								<view class="d-e-c mt10" v-if="item.status == 80 && item.isComment == 0">
									<button class="pay-btn theme-btn" @click="gotoEvaluate(item.orderId)">评价
									</button>
								</view>
							</view>
						</template>
					</view>
					<view class="order-bts">
						<!-- v-if="item.status ==10 || item.status ==30" 取消 -->
						<block>

							<!-- 已支付取消订单 -->
							<block v-if="item.cancel">
								<button @click="cancelOrder(item.orderId)" class="theme-borderbtn">取消订单</button>
							</block>
							<!-- 订单核销码 -->
							<!-- <block v-if="item.payStatus == 20 && item.deliveryType == 20 && item.deliveryStatus == 10">
								<button @click="onQRCode(item.orderId)" class="theme-borderbtn">核销码</button>
							</block> -->
							<!-- billId billStatus=10 -->
							<block v-if="item.billStatus == 10">
								<button class="theme-btn" @click="onPayOrder(item.billId)">付款</button>
							</block>
							<!-- 订单付款 不是线下付款 -->
							<!-- groupStatus 10  拼团中  20-已成团  30-未成团 -->
							<block v-if="item.status==10">
								<!-- 普通 -->
								<!-- <button v-if="item.orderType == 1" class="theme-btn" @click="onPayOrder(item.orderId)">付款</button> -->
								<button v-if="(item.orderType == 7 || item.orderType == 8) && item.groupStatus == 20"
									class="theme-btn" @click="onPayOrder(item.billId)">付款</button>
							</block>
							<!-- 支付尾款 -->
							<!-- refundStatus 10 未退款  20 退款中 30 退款成功 40 退款失败 -->
							<block v-if="item.status==30 && item.refundStatus == 10"><button class="theme-btn"
									@click="onPayFinalOrder(item.billId)">付尾款</button></block>
							<!-- 确认收货 -->
							<!-- <block v-if="item.deliveryStatus == 20 && item.receiptStatus == 10">
								<button v-if="item.payType==20 && item.paySource =='wx'" class="theme-btn"
									@click="wxOrder(item)">小程序确认收货</button>
								<button v-else class="theme-btn" @click="orderReceipt(item.orderId)">确认收货</button>
							</block> -->
						</block>
						<!-- 订单评价 -->
						<button class="theme-btn" v-if="item.status == 80 && item.isComment == 0"
							@click="gotoEvaluate(item.orderId)">评价</button>
						<template v-if="item.assembleStatus == 10 && item.orderType == 2">
							<button class="theme-btn"
								@click="gotoAssembleShare(item.product[0].billSourceId)">邀请好友拼单</button>
						</template>
					</view>
				</view>
				<view class="d-c-c p30" v-if="listData.length == 0 && !loading">
					<text class="iconfont icon-wushuju"></text>
					<text class="cont">亲，暂无相关记录哦</text>
				</view>
				<uni-load-more v-else :loadingType="loadingType"></uni-load-more>
			</view>
		</scroll-view>
		<!--核销二维码-->
		<Popup :show="isCodeImg" type="middle" @hidePopup="hideCodePopupFunc">
			<view class="ww100 p20 box-s-b">
				<image class="ww100" :src="codeImg" mode="widthFix"></image>
			</view>
		</Popup>
		<tabBar></tabBar>
	</view>
</template>

<script>
	import Popup from '@/components/uni-popup.vue';
	import uniLoadMore from '@/components/uni-load-more.vue';
	import {
		pay
	} from '@/common/pay.js';
	export default {
		components: {
			Popup,
			uniLoadMore
		},
		data() {
			return {
				/*手机高度*/
				phoneHeight: 0,
				/*可滚动视图区域高度*/
				scrollviewHigh: 0,
				/*状态选中*/
				state_active: 'all',
				/*顶部刷新*/
				topRefresh: false,
				/*数据*/
				listData: [],
				/*数据类别*/
				dataType: 'all',
				/*是否显示支付类别弹窗*/
				isPayPopup: false,
				/*支付方式*/
				pay_type: 20,
				/*订单id*/
				order_id: 0,
				/*最后一页码数*/
				last_page: 0,
				/*当前页面*/
				page: 1,
				/*每页条数*/
				list_rows: 10,
				/*有没有等多*/
				no_more: false,
				/*是否正在加载*/
				loading: true,
				/*是否显示核销二维码*/
				isCodeImg: false,
				codeImg: '',
				mchId: "",
				token: uni.getStorageSync('token'),
				UserState: uni.getStorageSync('UserState'),
			};
		},
		computed: {
			/*加载中状态*/
			loadingType() {
				if (this.loading) {
					return 1;
				} else {
					if (this.listData.length != 0 && this.no_more) {
						return 2;
					} else {
						return 0;
					}
				}
			}
		},
		onLoad(e) {
			if (typeof e.dataType != 'undefined') {
				this.dataType = e.dataType;
				this.state_active = this.dataType;
			}

		},
		mounted() {
			this.init();
		},
		onShow() {
			/*获取订单列表*/
			this.page = 1;
			this.listData = [];
			// 记录选择标签
			console.log(uni.getStorageSync('stateDataType'), 'stateDataType')
			if (uni.getStorageSync('stateDataType')) {
				this.dataType = uni.getStorageSync('stateDataType');
				this.state_active = this.dataType;
			}
			setTimeout(() => {
				this.getData();
			}, 600);
		},
		methods: {
			/*初始化*/
			init() {
				let self = this;
				uni.getSystemInfo({
					success(res) {
						self.phoneHeight = res.windowHeight;
						// 计算组件的高度
						let view = uni.createSelectorQuery().select('.top-tabbar');
						view.boundingClientRect(data => {
							if (data) {
								let h = self.phoneHeight - data.height;
								self.scrollviewHigh = h;
							}

						}).exec();
					}
				});
			},
			/*复制*/
			copy(message) {
				console.log("message", message)
				uni.setClipboardData({
					data: message, // 需要复制的内容
					success: () => {
						// 成功提示框显示 1 秒钟
						uni.showToast({
							title: '复制成功',
							icon: 'success',
							duration: 1000
						});
					},
					fail: () => {
						// 失败提示框显示 1 秒钟
						uni.showToast({
							title: '复制失败，请重试',
							icon: 'none',
							duration: 1000
						});
					}
				});
			},
			/*状态切换*/
			stateFunc(e) {
				let self = this;
				self.page = 1;
				self.loading = true;
				self.state_active = e;
				self.listData = [];
				self.dataType = e;
				self.getData();
				// 记录选择标签
				uni.setStorageSync('stateDataType', e);
			},

			/*可滚动视图区域到底触发*/
			scrolltolowerFunc() {
				let self = this;
				if (self.no_more) {
					return;
				}
				self.page++;
				if (self.page <= self.last_page) {
					self.getData();
				} else {
					self.no_more = true;
				}
			},

			/*获取数据*/
			getData() {
				let self = this;
				self.loading = true;
				let dataType = self.dataType;
				self._postBody(
					'user/order/lists', {
						type: dataType,
						pageIndex: self.page,
						pageSize: self.list_rows
					},
					function(res) {
						self.loading = false;
						self.listData = self.listData.concat(res.data.records);
						self.last_page = res.data.lastPage;
						if (res.data.records.length > 0) {
							self.mchId = res.data.records[0].mchId;
						}
						if (res.data.lastPage <= 1) {
							self.no_more = true;
						} else {
							self.no_more = false;
						}
					}
				);
			},
			/*计算时分秒*/
			countDown(t) {
				let time = new Date(t) / 1000 - (new Date() / 1000);
				//天数
				let day = Math.floor(time / (60 * 60 * 24));
				//取模（余数）
				let modulo = time % (60 * 60 * 24);
				//小时数
				let hour = Math.floor(modulo / (60 * 60));
				modulo = modulo % (60 * 60);
				//分钟
				let minute = Math.floor(modulo / 60);
				//秒
				let second = modulo % 60;
				day = this.convertTwo(day);
				hour = this.convertTwo(hour);
				minute = this.convertTwo(minute);
				second = this.convertTwo(second);
				let text = parseInt(day) > 0 ? (parseInt(day) + '天 ') : '' + parseInt(hour) + '时' + parseInt(minute) +
					'分' + parseInt(second) + '秒';
				return text
			},

			/*跳转页面*/
			gotoOrder(e) {
				this.gotoPage('/orderpages/order/order-detail?orderId=' + e);
			},

			/*隐藏支付方式*/
			hidePopupFunc() {
				this.isPayPopup = false;
			},

			/*去支付*/
			payTypeFunc(payType) {
				let self = this;
				self.isPayPopup = false;
				uni.showLoading({
					title: '加载中'
				});
				self._post(
					'user.order/pay', {
						payType: payType,
						order_id: self.order_id,
						pay_source: self.getPlatform()
					},
					function(res) {
						pay(res, self);
					}
				);
			},
			depositPay(e) {
				this.gotoPage('orderpages/order/saveOrder?order_type=retainage&order_id=' + e)
			},
			/*支付方式选择*/
			onPayOrder(orderId) {
				let self = this;
				self.gotoPage('/orderpages/order/cashier?orderId=' + orderId)
			},
			// 支付尾款
			onPayFinalOrder(orderId) {
				let self = this;
				self.gotoPage(`/orderpages/order/cashier?orderType=60&orderId=${orderId}`)
			},

			/*确认收货*/
			orderReceipt(orderId) {
				let self = this;
				wx.showModal({
					title: '提示',
					content: '您确定要收货吗?',
					success: function(o) {
						if (o.confirm) {
							uni.showLoading({
								title: '正在处理'
							});
							self._post(
								'user/order/receipt', {
									orderId: orderId
								},
								function(res) {
									uni.hideLoading();
									uni.showToast({
										title: res.msg,
										duration: 2000,
										icon: 'success'
									});
									self.listData = [];
									self.getData();
								}
							);
						} else {
							uni.showToast({
								title: '取消收货',
								duration: 1000,
								icon: 'none'
							});
						}
					}
				});
			},
			cancelAdvance(e) {
				let self = this;
				let order_id = e;
				uni.showModal({
					title: '提示',
					content: '您确定要取消吗?',
					success: function(o) {
						if (o.confirm) {
							uni.showLoading({
								title: '正在处理'
							});
							self._get(
								'plus/advance/order/cancelFront', {
									orderAdvanceId: order_id
								},
								function(res) {
									uni.hideLoading();
									uni.showToast({
										title: '操作成功',
										duration: 2000,
										icon: 'success'
									});
									self.listData = [];
									self.getData();
								}
							);
						}
					}
				});
			},
			/*取消订单*/
			cancelOrder(e) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '您确定要取消吗?',
					success: function(o) {
						if (o.confirm) {
							uni.showLoading({
								title: '正在处理'
							});
							self._post(
								'user/order/cancel', {
									orderId: e
								},
								function(res) {
									uni.hideLoading();
									uni.showToast({
										title: '操作成功',
										duration: 2000,
										icon: 'success'
									});
									self.listData = [];
									self.getData();
								}
							);
						}
					}
				});
			},
			nowOverTime(t) {

				let now = new Date().getTime();
				let time = new Date(t).getTime();
				return now >= time

			},
			/*去评论*/
			gotoEvaluate(e) {
				this.gotoPage('/orderpages/order/evaluate/evaluate?order_id=' + e);
			},

			/*核销码*/
			onQRCode(e) {
				let self = this;
				uni.showLoading({
					title: '加载中'
				});
				self._get(
					'user/order/qrcode', {
						orderId: e,
						source: self.getPlatform()
					},
					function(res) {
						uni.hideLoading();
						self.isCodeImg = true;
						self.codeImg = res.data;
					}
				);
			},
			/*关闭核销二维码*/
			hideCodePopupFunc() {
				this.isCodeImg = false;
			},

			/*分享拼团*/
			gotoAssembleShare(e) {
				let url = '/pluspage/plus/assemble/fight-group-detail/fight-group-detail?assembleBillId=' + e;
				this.gotoPage(url);
			},
			wxOrder(item) {
				let self = this;
				if (wx.openBusinessView) {
					wx.openBusinessView({
						businessType: 'weappOrderConfirm',
						extraData: {
							merchant_id: self.mchId,
							merchant_trade_no: item.tradeNo,
							transaction_id: item.transactionId
						},
						success() {
							self._post(
								'user/order/receipt', {
									orderId: item.orderId
								},
								function(res) {
									uni.showToast({
										title: res.msg,
										duration: 2000,
										icon: 'success'
									});
									self.listData = [];
									self.getData();
								}
							);
						},
						fail() {
							//dosomething
						},
						complete() {
							//dosomething
						}
					});
				} else {
					//引导用户升级微信版本
				}
			},
		}
	};
</script>

<style lang="scss">
	@import url("css/myorder.css");
</style>